<template>
  <div class="withdrawal app-container">
    <el-card class="box-card" style="margin-bottom: 10px;">
      <el-row :gutter="10">
        <el-col :xs="24" :sm="12" :lg="8">
          <el-date-picker
            v-model="params.date_time"
            type="datetimerange"
            start-placeholder="申请开始时间"
            end-placeholder="申请结束日期"
            format="YYYY-MM-DD HH:mm:ss"
            date-format="YYYY/MM/DD ddd"
            time-format="A hh:mm:ss"
            size="default"/>
        </el-col>

        <el-col :xs="24" :sm="12" :lg="6">
          <el-button size="default" type="primary" icon="Search" @click="handleQuery">查询</el-button>
          <el-button size="default" @click="handleResetQuery">重置</el-button>
          <el-button size="default" type="success" icon="CreditCard" @click="onOpenWithdrawal">发起提现</el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-card class="box-card" style="margin-bottom: 10px;">
      <el-row>
        <el-col :span="6">
          <el-statistic :value="storeInfo.bill_amount">
            <template #title>
              <div style="display: inline-flex; align-items: center">
                总收入
                <el-tooltip
                  effect="dark"
                  content="全部收入金额"
                  placement="top">
                  <el-icon style="margin-left: 4px" :size="12">
                    <Warning/>
                  </el-icon>
                </el-tooltip>
              </div>
            </template>
          </el-statistic>
        </el-col>
        <el-col :span="6">
          <el-statistic :value="storeInfo.bill_amount_withdrawn">
            <template #title>
              <div style="display: inline-flex; align-items: center">
                可提现金额
                <el-tooltip
                  effect="dark"
                  content="客户确认收货的订单收入金额"
                  placement="top">
                  <el-icon style="margin-left: 4px" :size="12">
                    <Warning/>
                  </el-icon>
                </el-tooltip>
              </div>
            </template>
          </el-statistic>
        </el-col>
        <el-col :span="6">
          <el-statistic :value="storeInfo.bill_amount_freeze">
            <template #title>
              <div style="display: inline-flex; align-items: center">
                冻结金额
                <el-tooltip
                  effect="dark"
                  content="客户未确认收货的订单收入金额"
                  placement="top">
                  <el-icon style="margin-left: 4px" :size="12">
                    <Warning/>
                  </el-icon>
                </el-tooltip>
              </div>
            </template>
          </el-statistic>
        </el-col>
      </el-row>
    </el-card>
    <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
      <el-tab-pane v-for="(value, key) in statusData" :key="key" :name="key" :label="value">
        <el-table v-loading="loading" :data="pageData">
          <el-table-column label="提现编号" prop="id"/>
          <el-table-column label="状态">
            <template #default="{row}">
              <div>
                <el-tag type="primary" v-if="row.status === 'approve'">待打款</el-tag>
                <el-tag type="success" v-else-if="row.status === 'pass'">已完成</el-tag>
                <el-tag type="danger" v-else-if="row.status === 'reject'">已驳回</el-tag>
                <div class="tips" v-if="row.remark">驳回理由：{{ row.remark }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="提现金额">
            <template #default="{row}">
              <span>￥{{ row.amount }}</span>
            </template>
          </el-table-column>
          <el-table-column label="手续费">
            <template #default="{row}">
              <span>￥{{ row.service_cost }}</span>
            </template>
          </el-table-column>
          <el-table-column label="实际打款金额">
            <template #default="{row}">
              <span>￥{{ row.real_amount }}</span>
            </template>
          </el-table-column>
          <el-table-column label="提现账户" width="250">
            <template #default="{row}">
              <div>银行支行：{{ row.bank_name }}</div>
              <div>银行卡号：{{ row.bank_code }}</div>
            </template>
          </el-table-column>
          <el-table-column label="申请时间" prop="created_at"/>
        </el-table>
        <pagination
          v-model:total="total"
          v-model:page="params.page"
          v-model:limit="params.size"
          @pagination="handleQuery"
        />
      </el-tab-pane>
    </el-tabs>

    <el-dialog
      v-model="dialogVisible"
      title="发起提现"
      :width="500"
      :before-close="handleClose">
      <div class="dialog-box">
        <div style="margin-bottom: 20px;">
          <el-select v-model="withdrawalForm.bank_id" size="large" placeholder="请选择银行卡">
            <el-option v-for="item in bankList" :key="item.id" :label="item.bank_name+'-'+item.code" :value="item.id"/>
            <template #footer>
              <el-button v-if="!isAdding" size="large" @click="isAdding = true" style="width: 100%;" icon="Plus">添加银行卡
              </el-button>
              <template v-else>
                <div style="margin-bottom: 10px;">
                  <el-input v-model="bankForm.bank_name" size="large" class="option-input" placeholder="请输入开户行名称"/>
                </div>
                <div style="margin-bottom: 10px;">
                  <el-input v-model="bankForm.code" size="large" class="option-input" placeholder="请输入银行卡号码"/>
                </div>
                <div style="text-align: center;">
                  <el-button size="large" @click="isAdding = false">取消</el-button>
                  <el-button size="large" type="primary" :loading="addLoading" @click="onConfirmBank">确定</el-button>
                </div>
              </template>
            </template>
          </el-select>
        </div>
        <div>
          <el-input size="large" v-model="withdrawalForm.amount" placeholder="请输入提现金额"
                    :formatter="(value) => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                    :parser="(value) => value.replace(/\￥\s?|(,*)/g, '')"
          ></el-input>
          <div class="tips">可提现金额：￥{{ storeInfo.bill_amount_withdrawn }}</div>
        </div>

        <div class="draw-notice">
          <div class="title">提现说明</div>
          <div class="draw-list">1.单次最低提现 100 元，最高提现(元): 不限；</div>
          <div class="draw-list">2.每日最多可提现次数: 不限；每日最多提现金额(元): 不限；</div>
          <div class="draw-list">3.每笔收取提现手续费 {{ config.value*100 }}%；</div>
          <div class="draw-list">4.提现结果请查收对应渠道服务通知；</div>
          <div class="draw-list">5.如有疑问请及时联系客服。</div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="large" @click="handleClose">关闭</el-button>
          <el-button size="large" type="primary" @click="onAddWithdrawal">提现</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted} from "vue";
import AuthAPI from '@/api/auth/index'
import FinanceAPI from '@/api/finance/finance'
import type {TabsPaneContext} from 'element-plus'
import {useUserStore} from "@/store";

const userStore = useUserStore();
const statusData = ref({
  'all': '全部',
  'approve': '待打款',
  'pass': '已完成',
  'reject': '已驳回',
})
const params = ref({
  status: "",
  page: 1,
  size: 15,
});
const withdrawalForm = ref({
  amount: 0,
  bank_id: "",
});
const bankForm = ref({
  bank_name: "",
  code: ""
});
const bankList = ref([]);
const dialogVisible = ref(false);
const isAdding = ref(false);
const total = ref(0);
const loading = ref(false);
const addLoading = ref(false);
const pageData = ref([]);
const storeInfo = ref({});
const activeName = ref('all');

const handleClick = (tab: TabsPaneContext, event: Event) => {
  activeName.value = tab.paneName;
  params.value.status = tab.paneName == 'all' ? '' : tab.paneName;
  params.value.page = 1;
  handleQuery();
}

function onOpenWithdrawal() {
  dialogVisible.value = true;
}

function handleClose() {
  withdrawalForm.value = {
    amount: 0,
    bank_id: "",
  };
  dialogVisible.value = false;
}

function getBankData() {
  FinanceAPI.getAccountBank().then((data: any) => {
    bankList.value = data;
  })
}

function onConfirmBank() {
  addLoading.value = true;
  FinanceAPI.addAccountBank(bankForm.value).then((res: any) => {
    bankForm.value = {
      bank_name: "",
      code: ""
    };
    isAdding.value = false;
    addLoading.value = false;
    getBankData();
  }).catch(error => {
    addLoading.value = false;

  })
}

function onAddWithdrawal() {
  if (!withdrawalForm.value.bank_id) {
    return ElMessage.info("请选择银行卡号")
  }
  if (!withdrawalForm.value.amount) {
    return ElMessage.info("请输入提现金额")
  } else {
    if (withdrawalForm.value.amount < 100) {
      return ElMessage.info("单次最低提现 100元！")
    } else if (withdrawalForm.value.amount > storeInfo.value.bill_amount_withdrawn) {
      return ElMessage.info("提现金额不能大于可提现金额！")
    }
  }


  FinanceAPI.addWithdrawn(withdrawalForm.value).then(res => {
    withdrawalForm.value = {
      amount: 0,
      bank_id: ""
    }
    dialogVisible.value = false;
    getStoreInfo();
    handleQuery();
  })
}

function handleResetQuery() {

}

function handleQuery() {
  loading.value = true;
  FinanceAPI.getWithdrawnLog(params.value).then((res: any) => {
    pageData.value = res.records;
    total.value = res.total_page;
    loading.value = false;
  })
    .finally(() => {
      loading.value = false;
    });
}

function getStoreInfo() {
  AuthAPI.supplierInfo().then((res: any) => {
    if (res.data.is_supplier) {
      storeInfo.value = res.data.info;
    }
  })
}

onMounted(() => {
  userStore.getSystemConfig();
  getStoreInfo();
  getBankData();
  handleQuery();
})

const config = computed(() => userStore.config);
</script>

<style scoped lang="scss">
.withdrawal {

  .el-col {
    text-align: center;
  }

  .el-statistic {
    --el-statistic-content-font-size: 28px;
  }

  .dialog-box {
    padding: 10px;

    .tips {
      color: #ff0000;
      margin-top: 5px;
    }

    .draw-notice {
      margin-top: 30px;
    }
  }
}
</style>
